const pdfjsLib = require("pdfjs-dist/legacy/build/pdf.js");
const PdfjsWorker = require("worker-loader?esModule=false&filename=[name].js!pdfjs-dist/legacy/build/pdf.worker.min.js");

if (typeof window !== "undefined" && "Worker" in window) {
    pdfjsLib.GlobalWorkerOptions.workerPort = new PdfjsWorker();
}

import * as pdfjsViewer from 'pdfjs-dist/legacy/web/pdf_viewer';

import BaseDocumentViewerView from "./BaseDocumentViewerView";

/** PDF viewer using pdf.js
 *
 * Features :
 *  - zoom/unzoom
 *  - multipage
 *  - text selection (for copy/paste use)
 *
 *  Advanced features are willingly disabled (forms, links, scripting)
 *
 *  Events triggered
 *    - loader:start (start of network load)
 *    - loader:stop (end of network load, whatever the result)
 */
const PDFViewerView = BaseDocumentViewerView.extend({
    initialize(options) {
        PDFViewerView.__super__.initialize.apply(this, arguments);
        this.pdfDocument = null;
        this.viewer = null;
    },
    onPagePrevious(){
        this.viewer.previousPage();
    },
    onPageNext(){
        this.viewer.nextPage();
    },
    zoom(factor){
        let container = this.ui.document_container[0];
        const xScroll = this.getXScroll(container, factor);
        const yScroll = this.getYScroll(container, factor);

        this.viewer.currentScale = this.viewer.currentScale * factor;

        container.scroll(xScroll, yScroll);
    },
    onRender(){
        const eventBus = new pdfjsViewer.EventBus();
        const pdfViewer = new pdfjsViewer.PDFViewer({
            container: this.ui.document_container[0],
            eventBus: eventBus,
        });

        eventBus.on("pagesinit", function () {
            pdfViewer.currentScaleValue = "page-width";
        });

        this.showLoader();
        let this_ = this;  // Won't work with a bind() because of workers I guess
        pdfjsLib.getDocument(this.fileUrl).promise
            .then(function (pdfDocument) {
                this_.hideLoader();
                pdfViewer.setDocument(pdfDocument);
                this_.pdfDocument = pdfDocument;
                this_.renderControls(this_);
            })
            .catch(function (reason) {
                this_.hideLoader();
                console.error("Error: " + reason);
                alert("Erreur lors de l'affichage du PDF");
            });
        this.viewer = pdfViewer;
    },
    isMultipage(){
        return this.pdfDocument.numPages > 1;
    },
});
export default PDFViewerView;
